package com.meihuayishu.backend.service.impl;

import com.meihuayishu.backend.dto.DivinationResult;
import com.meihuayishu.backend.service.CacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class CacheServiceImpl implements CacheService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    @Override
    public void cacheDivinationResult(String key, DivinationResult result, long timeout) {
        try {
            redisTemplate.opsForValue().set(key, result, timeout, TimeUnit.SECONDS);
            log.debug("缓存占卜结果成功，key: {}", key);
        } catch (Exception e) {
            log.error("缓存占卜结果失败，key: {}", key, e);
        }
    }
    
    @Override
    public DivinationResult getDivinationResult(String key) {
        try {
            Object result = redisTemplate.opsForValue().get(key);
            if (result instanceof DivinationResult) {
                log.debug("从缓存获取占卜结果成功，key: {}", key);
                return (DivinationResult) result;
            }
            log.debug("缓存中未找到占卜结果，key: {}", key);
            return null;
        } catch (Exception e) {
            log.error("从缓存获取占卜结果失败，key: {}", key, e);
            return null;
        }
    }
    
    @Override
    public void evictCache(String key) {
        try {
            redisTemplate.delete(key);
            log.debug("删除缓存成功，key: {}", key);
        } catch (Exception e) {
            log.error("删除缓存失败，key: {}", key, e);
        }
    }
}